from typing import List
from flask import request, jsonify, send_file

from database.db import get_db


def configure_record(app):

    # 获取所有样本集
    @app.route('/record', methods=['GET', 'POST'])
    def record():
        db = get_db()
        if (request.method == 'GET'):  # 获取样本集
            dataset_id_get = request.args.get('datasetId')
            datasets = db.execute(
                'SELECT * FROM dataset_record where dataset_id = ' +
                str(dataset_id_get)).fetchall()
            data = {'dataList': []}
            for item in datasets:
                obj = {
                    'id': item[0],
                    'datasetId': item[1],
                    'clarity': item[2],
                    'contrast': item[3],
                    'brightness': item[4],
                    'imagePath': item[5],
                    'labelPath': item[6]
                }
                data['dataList'].append(obj)
            return jsonify(data)
        else:  # 插入一个样本集

            # 获取字符串类型的数据
            dataset_id = request.form['datasetId']
            # 查表获取对应样本集绝对路径
            result = db.execute("select path from dataset where id = " +
                                str(dataset_id)).fetchone()
            path = result['path']
            # print(path)

            # 获取图片文件
            image_file = request.files['imageFile']
            # 保存图片文件
            image_path = path + '/images/' + image_file.filename
            image_file.save(image_path)

            # 获取标签文件
            label_file = request.files['labelFile']
            # 保存标签文件
            label_path = path + '/labels/' + label_file.filename
            label_file.save(label_path)

            # 使用参数化查询以避免 SQL 注入
            query = 'INSERT INTO dataset_record (dataset_id, clarity, contrast, brightness, image_path, ' \
                    'label_path) VALUES (?, 1, 1, 1, ?, ?);'
            db.execute(query, (dataset_id, image_path, label_path))
            db.commit()

            data = {"code": 0, "msg": ""}
            return jsonify(data)

    @app.route('/record/image', methods=['GET'])
    def get_img():
        db = get_db()
        image_id = request.args.get('id')
        result = db.execute(
            'SELECT image_path FROM dataset_record where id = ' +
            str(image_id)).fetchone()
        image_path = result['image_path']

        # 使用 send_file 发送图片文件
        return send_file(image_path, mimetype='image/jpeg')
